<template>
  <div class="water-price-container">
    <!-- 顶部添加水价按钮 -->
    <div class="header page-title">
      水源单价设置
      <el-button type="primary" icon="Plus" @click="openAddTypeDialog">添加水源类型</el-button>
    </div>
    <!-- 使用v-for渲染所有水源类型卡片 -->
    <el-card shadow="hover" class="water-type-card" v-for="(type, index) in waterTypes" :key="index">
      <template #header>
        <span class="card-title">{{ type.name }}</span>
      </template>

      <div class="card-content">
        <el-row :gutter="20">
          <!-- 左侧编辑区 -->
          <el-col :span="8">
            <div class="left-content">
              <!-- 当前价格信息 -->
              <div class="price-info">
                <div class="current-price">
                  <span class="label">当前单价：</span>
                  <span class="price">{{ getCurrentPrice(type.id) }}</span>
                  <span class="unit">元/m³</span>
                </div>
                <el-button type="primary" class="update-btn" @click="openUpdateDialog(type.id)">更新水价</el-button>
              </div>

              <!-- 表计信息 -->
              <div class="meter-info">
                <div class="meter-label">该水源类型一级表：</div>
                <div class="meter-code">{{ type.meterCode }}</div>
              </div>

              <div class="action-buttons">
                <el-button plain>添加</el-button>
              </div>
            </div>
          </el-col>

          <!-- 右侧价格图表 -->
          <el-col :span="16">
            <div class="chart-area">
              <StepChart :chartData="getChartDataForType(type.id)" :height="'240px'"
                @pointClick="(params) => handleChartPointClick(params, type.id)" />
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 更新水价对话框 -->
    <el-dialog v-model="showUpdateDialog" title="更新水价" width="30%" :close-on-click-modal="false">
      <div class="update-form">
        <el-form :model="updateForm" label-position="left" label-width="140px">
          <el-form-item label="新单价">
            <el-input v-model="updateForm.price" placeholder="请输入新水价">
              <template #append>元/m³</template>
            </el-input>
          </el-form-item>
          <el-form-item label="新单价开始执行日">
            <el-date-picker v-model="updateForm.date" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUpdateDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdatePrice">更新</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加水源类型对话框 -->
    <el-dialog v-model="showAddTypeDialog" title="添加水源类型" width="40%" :close-on-click-modal="false">
      <div class="add-type-form">
        <el-form :model="addTypeForm" label-position="left" label-width="140px" :rules="addTypeRules"
          ref="addTypeFormRef">
          <el-form-item label="水源类型名称" prop="name">
            <el-input v-model="addTypeForm.name" placeholder="请输入水源类型名称"></el-input>
          </el-form-item>
          <el-divider>初始水价信息</el-divider>
          <el-form-item label="初始水价" prop="initialPrice">
            <el-input v-model="addTypeForm.initialPrice" placeholder="请输入初始水价">
              <template #append>元/m³</template>
            </el-input>
          </el-form-item>
          <el-form-item label="生效日期" prop="initialDate">
            <el-date-picker v-model="addTypeForm.initialDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddTypeDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddType">添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认修改已有水价的对话框 -->
    <el-dialog v-model="showConfirmDialog" title="确认修改" width="30%">
      <span>该时间段已存在水价数据，是否要覆盖修改？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConfirmDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmOverwritePrice">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import StepChart from '@/components/chart/BaseStepChart.vue';

// 定义水源类型
const waterTypes = ref([
  {
    id: 'municipal',
    name: '市政供水',
    meterCode: 'I-01'
  },
  {
    id: 'underground',
    name: '地下水',
    meterCode: '2-05'
  },
  {
    id: 'tap',
    name: '自来水',
    meterCode: 'T-03'
  },
  {
    id: 'surface',
    name: '地表水',
    meterCode: 'S-07'
  }
]);

// 所有水源类型的价格历史数据
const priceHistories = ref({
  municipal: [
    { id: 1, date: '2022-01-01', price: 3.28 },
    { id: 2, date: '2022-06-01', price: 3.38 },
    { id: 4, date: '2023-07-01', price: 3.58 },
  ],
  underground: [
    { id: 1, date: '2022-01-01', price: 3.38 },
    { id: 2, date: '2022-06-01', price: 3.48 },
    { id: 3, date: '2023-07-01', price: 3.58 },
    { id: 4, date: '2024-01-01', price: 5.10 }
  ],
  tap: [
    { id: 1, date: '2022-01-01', price: 2.80 },
    { id: 2, date: '2022-08-01', price: 2.95 },
    { id: 3, date: '2023-03-01', price: 3.20 },
    { id: 4, date: '2023-11-01', price: 3.40 },
    { id: 5, date: '2024-02-01', price: 3.75 }
  ],
  surface: [
    { id: 1, date: '2022-01-01', price: 2.10 },
    { id: 2, date: '2022-05-01', price: 2.30 },
    { id: 3, date: '2023-02-01', price: 2.50 },
    { id: 4, date: '2023-10-01', price: 2.65 },
    { id: 5, date: '2024-01-01', price: 2.95 }
  ]
});

// 更新表单
const updateForm = reactive({
  typeId: '',
  price: '',
  date: '',
  id: null
});

// 添加水源类型表单
const addTypeForm = reactive({
  name: '',
  initialPrice: '',
  initialDate: dayjs().format('YYYY-MM-DD')
});

// 添加水源类型表单验证规则
const addTypeRules = {
  name: [
    { required: true, message: '请输入水源类型名称', trigger: 'blur' },
  ],
  initialPrice: [
    { required: true, message: '请输入初始水价', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的价格(最多两位小数)', trigger: 'blur' }
  ],
  initialDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' },
  ]
};

// 表单ref
const addTypeFormRef = ref(null);

// 控制对话框显示
const showUpdateDialog = ref(false);
const showConfirmDialog = ref(false);
const showAddTypeDialog = ref(false);

// 存储图表点击的索引映射
const chartDataIndexMap = reactive({});

// 获取指定水源类型的当前价格
const getCurrentPrice = (typeId) => {
  const history = priceHistories.value[typeId] || [];
  if (history.length === 0) return '0.00';

  // 按日期排序并获取最新的价格
  const sortedPrices = [...history].sort((a, b) => {
    return dayjs(b.date).valueOf() - dayjs(a.date).valueOf();
  });

  return sortedPrices[0].price.toFixed(2);
};

// 获取指定类型的图表数据
const getChartDataForType = (typeId) => {
  const history = priceHistories.value[typeId] || [];
  const typeName = waterTypes.value.find(type => type.id === typeId)?.name || '';

  const { data, indexMap } = getChartData(history, `${typeName}价格`);
  chartDataIndexMap[typeId] = indexMap;
  return data;
};

// 获取图表数据通用方法
const getChartData = (priceHistory, seriesName) => {
  // 按日期排序
  const sortedPrices = [...priceHistory].sort((a, b) => {
    return dayjs(a.date).valueOf() - dayjs(b.date).valueOf();
  });
  // 创建索引映射以便正确处理点击事件
  const indexMap = sortedPrices.map(item => item.id);

  // 转换为图表所需格式
  const xAxisData = sortedPrices.map(item => {
    const date = dayjs(item.date).format('YYYY-MM-DD');
    return date;
  });


  xAxisData.push('至今');

  const seriesData = sortedPrices.map(item => item.price);
  // 添加最后一个点，与最后一个价格相同
  if (seriesData.length > 0) {
    seriesData.push(seriesData[seriesData.length - 1]);
  }

  return {
    data: {
      xAxisData: xAxisData,
      series: [
        {
          name: seriesName,
          type: 'line',
          step: 'end',
          data: seriesData,
          emphasis: {
            itemStyle: {
              color: '#409EFF'
            }
          }
        }
      ]
    },
    indexMap
  };
};

// 打开更新对话框
const openUpdateDialog = (typeId) => {
  updateForm.typeId = typeId;
  updateForm.price = '';
  updateForm.date = dayjs().format('YYYY-MM-DD');
  updateForm.id = null;
  showUpdateDialog.value = true;
};

// 打开添加水源类型对话框
const openAddTypeDialog = () => {
  // 重置表单
  if (addTypeFormRef.value) {
    addTypeFormRef.value.resetFields();
  }

  // 设置默认值
  addTypeForm.name = '';
  addTypeForm.initialPrice = '';
  addTypeForm.initialDate = dayjs().format('YYYY-MM-DD');

  showAddTypeDialog.value = true;
};

// 添加新水价
const addNewPrice = (typeId) => {
  openUpdateDialog(typeId);
};

// 编辑水价
const editPrice = (priceData, typeId) => {
  updateForm.typeId = typeId;
  updateForm.price = priceData.price.toString();
  updateForm.date = priceData.date;
  updateForm.id = priceData.id;
  showUpdateDialog.value = true;
};

// 处理图表点击事件
const handleChartPointClick = (params, typeId) => {
  // 获取点击的价格点对应的数据
  const index = params.dataIndex;
  const priceHistory = priceHistories.value[typeId] || [];
  const indexMap = chartDataIndexMap[typeId] || [];

  // 确保不是最后一个"至今"点且索引有效
  if (index < indexMap.length) {
    const id = indexMap[index];
    const priceData = priceHistory.find(item => item.id === id);

    if (priceData) {
      editPrice(priceData, typeId);
    }
  }
};

// 确认更新水价
const confirmUpdatePrice = () => {
  if (!updateForm.price || !updateForm.date) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  // 检查数字格式
  if (isNaN(parseFloat(updateForm.price)) || parseFloat(updateForm.price) <= 0) {
    ElMessage.warning('请输入有效的价格');
    return;
  }

  const priceHistory = priceHistories.value[updateForm.typeId] || [];

  // 检查日期是否已存在价格（除了当前编辑的记录）
  const existingPrice = priceHistory.find(item =>
    item.date === updateForm.date && (!updateForm.id || item.id !== updateForm.id)
  );

  if (existingPrice) {
    showConfirmDialog.value = true;
    return;
  }

  // 直接更新或添加价格
  savePrice();
};

// 确认添加水源类型
const confirmAddType = () => {
  addTypeFormRef.value.validate((valid) => {
    if (!valid) {
      return;
    }

    // 自动生成ID (使用拼音首字母或简化的英文)
    const timestamp = Date.now().toString().slice(-6);
    const typeId = `water_type_${timestamp}`;

    // 自动生成表计编号
    const randomCode = Math.floor(Math.random() * 90 + 10);
    const meterCode = `${addTypeForm.name.charAt(0).toUpperCase()}-${randomCode}`;

    // 添加新的水源类型
    const newType = {
      id: typeId,
      name: addTypeForm.name,
      meterCode: meterCode
    };

    waterTypes.value.push(newType);

    // 初始化价格历史
    priceHistories.value[typeId] = [
      {
        id: 1,
        date: addTypeForm.initialDate,
        price: parseFloat(addTypeForm.initialPrice)
      }
    ];

    ElMessage.success('水源类型添加成功');
    showAddTypeDialog.value = false;
  });
};

// 确认覆盖已有价格
const confirmOverwritePrice = () => {
  showConfirmDialog.value = false;
  savePrice();
};

// 保存水价
const savePrice = () => {
  const typeId = updateForm.typeId;
  const priceHistory = priceHistories.value[typeId] || [];
  const newPrice = {
    price: parseFloat(updateForm.price),
    date: updateForm.date
  };

  if (updateForm.id) {
    // 更新已有价格
    const index = priceHistory.findIndex(item => item.id === updateForm.id);
    if (index !== -1) {
      priceHistory[index] = {
        ...priceHistory[index],
        ...newPrice
      };
    }
  } else {
    // 添加新价格
    const maxId = priceHistory.length > 0
      ? Math.max(...priceHistory.map(item => item.id)) + 1
      : 1;


    priceHistory.push({
      date: newPrice.date,
      price: newPrice.price,
      id: maxId
    });
  }


  ElMessage.success(updateForm.id ? '水价更新成功' : '新水价添加成功');
  showUpdateDialog.value = false;
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.water-price-container {
  display: flex;
  flex-direction: column;
  gap: var(--gap-normal);
}

.water-type-card {
  margin-bottom: var(--gap-normal);
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

.edit-button {
  margin-left: 5px;
}

.card-content {
  padding: 10px 0;
}

.left-content {
  display: flex;
  flex-direction: column;
  gap: var(--gap-normal);
}

/* 当前价格样式 */
.price-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.current-price {
  display: flex;
  align-items: center;
}

.current-price .label {
  font-size: 14px;
  margin-right: 5px;
}

.current-price .price {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-right: 5px;
}

.current-price .unit {
  color: #606266;
}

.update-btn {
  align-self: flex-start;
}

/* 表计信息样式 */
.meter-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.meter-label {
  font-size: 14px;
  color: #606266;
}

.meter-code {
  display: inline-block;
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 5px 15px;
  border-radius: 4px;
  font-size: 14px;
}

.action-buttons {
  margin-top: 10px;
}

.chart-area {
  height: 240px;
  width: 100%;
}

.update-form,
.add-type-form {
  padding: 0 var(--gap-normal);
}

.add-type-form .el-divider {
  margin: 24px 0 16px;
}
</style>